package com.luych.toolbox.automation.service.service;

import com.luych.toolbox.automation.service.constant.Constant;
import com.luych.toolbox.automation.service.dao.AutoSshServerDao;
import com.luych.toolbox.automation.service.entity.AutoSshServer;
import com.luych.toolbox.automation.service.job.AutoSshServerHealthCheckJob;
import com.luych.toolbox.common.enums.AutoSshServerStatus;
import com.luych.toolbox.common.feign.intf.base.service.UserFeign;
import com.luych.toolbox.common.feign.param.automation.service.AutoSshServerParam;
import com.luych.toolbox.common.feign.view.automation.service.AutoSshServerView;
import com.luych.toolbox.common.feign.view.base.service.UserView;
import com.luych.toolbox.common.page.PageParam;
import com.luych.toolbox.common.page.PageResult;
import com.luych.toolbox.common.service.base.BaseConvert;
import com.luych.toolbox.common.service.base.BaseService;
import com.luych.toolbox.common.service.exception.HttpException;
import com.luych.toolbox.common.service.page.SpringPageParamAdapter;
import com.luych.toolbox.common.service.page.SpringPageResultAdapter;
import org.quartz.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.data.domain.Page;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;

@Service
public class AutoSshServerService extends BaseService<AutoSshServerView, AutoSshServerParam, AutoSshServer>
        implements ApplicationListener<ApplicationReadyEvent> {

    private static final BaseConvert<AutoSshServerParam, AutoSshServer> sshServerParamToEntity = AutoSshServer::new;
    private static final BaseConvert<AutoSshServer, AutoSshServerView> sshServerEntityToView = AutoSshServerView::new;

    private final Boolean rescheduleWhenStart;
    private final Scheduler scheduler;
    private final AutoSshServerDao sshServerDao;
    private final UserFeign userFeign;

    @Autowired
    public AutoSshServerService(@Value("${spring.quartz.rescheduleWhenStart:false}") Boolean rescheduleWhenStart,
                                Scheduler scheduler,
                                AutoSshServerDao sshServerDao,
                                UserFeign userFeign) {
        super(sshServerDao, sshServerParamToEntity, sshServerEntityToView);
        this.rescheduleWhenStart = rescheduleWhenStart;
        this.scheduler = scheduler;
        this.sshServerDao = sshServerDao;
        this.userFeign = userFeign;
    }

    @Override
    protected AutoSshServerView fill(AutoSshServerView view) {
        sshServerDao.findById(view.getId()).map(AutoSshServer::getOwnerId).map(userFeign::get).ifPresent(view::setOwner);
        return view;
    }

    @Override
    public AutoSshServerView save(AutoSshServerParam param) {
        // check owner
        UserView owner = userFeign.get(param.getOwnerId());
        if (owner == null) {
            throw new HttpException(HttpStatus.BAD_REQUEST, Constant.SSH_SERVER_SAVE_OWNER_ERROR);
        }
        // save docker server
        AutoSshServer sshServerParam = sshServerParamToEntity.apply(param);
        sshServerParam.setStatus(AutoSshServerStatus.WAITING);
        AutoSshServer sshServerResult = sshServerDao.save(sshServerParam);
        return this.fill(sshServerEntityToView.apply(sshServerResult));
    }

    private JobKey getJobKey(String id, Class<? extends Job> clazz) {
        return new JobKey(id, clazz.getName());
    }

    private JobDetail getJobDetail(String id, Class<? extends Job> clazz) {
        Map<String, Object> jobParam = new HashMap<String, Object>() {{
            this.put("id", id);
        }};
        return JobBuilder.newJob(clazz)
                .withIdentity(this.getJobKey(id, clazz))
                .usingJobData(new JobDataMap(jobParam))
                .build();
    }

    private Trigger getJobTrigger(String id, Class<? extends Job> clazz, int second) {
        return TriggerBuilder.newTrigger()
                .withIdentity(id, clazz.getName())
                .withSchedule(SimpleScheduleBuilder.repeatSecondlyForever(second))
                .build();
    }

    @Override
    public AutoSshServerView create(AutoSshServerParam param) {
        Assert.notNull(param.getName(), "Param name can't be empty");
        Assert.notNull(param.getHost(), "Param host can't be empty");
        Assert.notNull(param.getPort(), "Param port can't be empty");
        Assert.notNull(param.getUser(), "Param user can't be empty");
        Assert.notNull(param.getPass(), "Param pass can't be empty");
        Assert.notNull(param.getOwnerId(), "Param ownerId can't be empty");

        // check name exists
        if (sshServerDao.findByName(param.getName()).isPresent()) {
            throw new HttpException(HttpStatus.CONFLICT, Constant.SSH_SERVER_SAVE_NAME_USED);
        }

        // save
        AutoSshServerView view = this.save(param);

        // schedule
        try {
            scheduler.scheduleJob(
                    this.getJobDetail(view.getId(), AutoSshServerHealthCheckJob.class),
                    this.getJobTrigger(view.getId(), AutoSshServerHealthCheckJob.class, 600)
            );
        } catch (SchedulerException e) {
            throw new IllegalStateException(e);
        }

        // return
        return view;
    }

    @Override
    public AutoSshServerView modify(AutoSshServerParam param) {
        Assert.notNull(param.getId(), "Param id can't be empty");
        Assert.notNull(param.getName(), "Param name can't be empty");
        Assert.notNull(param.getHost(), "Param host can't be empty");
        Assert.notNull(param.getPort(), "Param port can't be empty");
        Assert.notNull(param.getUser(), "Param user can't be empty");
        Assert.notNull(param.getPass(), "Param pass can't be empty");
        Assert.notNull(param.getOwnerId(), "Param ownerId can't be empty");

        // check name exists
        Optional<AutoSshServer> sshServerOptOfName = sshServerDao.findByName(param.getName());
        if (sshServerOptOfName.isPresent() && !sshServerOptOfName.get().getId().equals(param.getId())) {
            throw new HttpException(HttpStatus.CONFLICT, Constant.SSH_SERVER_SAVE_NAME_USED);
        }

        // save
        AutoSshServerView view = this.save(param);

        // schedule
        try {
            scheduler.deleteJob(this.getJobKey(view.getId(), AutoSshServerHealthCheckJob.class));
            scheduler.scheduleJob(
                    this.getJobDetail(view.getId(), AutoSshServerHealthCheckJob.class),
                    this.getJobTrigger(view.getId(), AutoSshServerHealthCheckJob.class, 600)
            );
        } catch (SchedulerException e) {
            throw new IllegalStateException(e);
        }

        // return
        return view;
    }

    @Override
    public void remove(String id) {
        // schedule
        try {
            scheduler.deleteJob(this.getJobKey(id, AutoSshServerHealthCheckJob.class));
        } catch (SchedulerException e) {
            throw new IllegalStateException(e);
        }

        // delete
        sshServerDao.deleteById(id);
    }

    public PageResult<AutoSshServerView> pageByKeyword(PageParam pageParam, String keyword) {
        Page<AutoSshServer> page;
        if (StringUtils.isEmpty(keyword)) {
            page = sshServerDao.findAll(new SpringPageParamAdapter(pageParam));
        } else {
            page = sshServerDao.findByNameLikeOrHostLike('%' + keyword + '%', '%' + keyword + '%', new SpringPageParamAdapter(pageParam));
        }
        PageResult<AutoSshServer> pageResult = new SpringPageResultAdapter<>(page);
        return pageResult.convert(sshServerEntityToView).convert(this::fill);
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        if (Boolean.TRUE.equals(rescheduleWhenStart)) {
            List<AutoSshServer> sshServers = sshServerDao.findAll();
            for (AutoSshServer SshServer : sshServers) {
                try {
                    scheduler.deleteJob(this.getJobKey(SshServer.getId(), AutoSshServerHealthCheckJob.class));
                    scheduler.scheduleJob(
                            this.getJobDetail(SshServer.getId(), AutoSshServerHealthCheckJob.class),
                            this.getJobTrigger(SshServer.getId(), AutoSshServerHealthCheckJob.class, 600)
                    );
                } catch (SchedulerException e) {
                    throw new IllegalStateException(e);
                }
            }
        }
    }
}
